// MainActivity.java
package com.example.finalproject;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private RecyclerView todoRecyclerView;
    private TodoAdapter todoAdapter;
    private ArrayList<String> todoList = new ArrayList<>();
    private ArrayList<String> originalTodoList = new ArrayList<>();
    private TextView statsTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化UI组件
        todoRecyclerView = findViewById(R.id.rv_todo_list);
        FloatingActionButton addFab = findViewById(R.id.fab_add_todo);
        statsTextView = findViewById(R.id.tv_stats);
        Button sortBtn = findViewById(R.id.btn_sort);
        Button deleteDoneBtn = findViewById(R.id.btn_delete_done);
        EditText searchInput = findViewById(R.id.et_search);
        Button searchBtn = findViewById(R.id.btn_search);

        // 配置RecyclerView
        todoRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        todoAdapter = new TodoAdapter(todoList);
        todoRecyclerView.setAdapter(todoAdapter);

        // 加载存储的待办事项
        loadTodoList();
        updateStats();

        // 添加按钮点击事件
        addFab.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, AddTodoActivity.class);
            startActivityForResult(intent, 1001);
        });

        // 列表项长按删除
        todoAdapter.setOnItemLongClickListener(position -> {
            showDeleteDialog(position);
        });

        // 点击列表项切换完成状态
        todoAdapter.setOnItemClickListener(position -> {
            todoAdapter.toggleComplete(position);
            saveTodoList();
            updateStats();
        });

        // 排序按钮
        sortBtn.setOnClickListener(v -> sortTodoList());

        // 批量删除已完成
        deleteDoneBtn.setOnClickListener(v -> deleteAllCompleted());

        // 搜索功能
        searchBtn.setOnClickListener(v -> {
            String keyword = searchInput.getText().toString().trim();
            filterTodoList(keyword);
        });

        // 设置滑动操作
        ItemTouchHelper.SimpleCallback touchCallback = new ItemTouchHelper.SimpleCallback(
                0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT
        ) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView,
                                  @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                if (direction == ItemTouchHelper.LEFT) {
                    todoList.remove(position);
                    todoAdapter.notifyItemRemoved(position);
                    originalTodoList.clear();
                    originalTodoList.addAll(todoList);
                    saveTodoList();
                    updateStats();
                    Toast.makeText(MainActivity.this, "已删除待办", Toast.LENGTH_SHORT).show();
                } else if (direction == ItemTouchHelper.RIGHT) {
                    todoAdapter.toggleComplete(position);
                    saveTodoList();
                    updateStats();
                }
            }
        };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(touchCallback);
        itemTouchHelper.attachToRecyclerView(todoRecyclerView);
    }

    private void showDeleteDialog(int position) {
        new AlertDialog.Builder(this)
                .setTitle("删除待办")
                .setMessage("确定要删除这条待办吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    todoList.remove(position);
                    originalTodoList.clear();
                    originalTodoList.addAll(todoList);
                    todoAdapter.notifyItemRemoved(position);
                    saveTodoList();
                    updateStats();
                    Toast.makeText(MainActivity.this, "已删除待办事项", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            String newTodo = data.getStringExtra("todo_content");
            todoList.add(newTodo);
            originalTodoList.clear();
            originalTodoList.addAll(todoList);
            todoAdapter.notifyItemInserted(todoList.size() - 1);
            saveTodoList();
            updateStats();
        }
    }

    private void saveTodoList() {
        getSharedPreferences("todo_data", MODE_PRIVATE)
                .edit()
                .putStringSet("todo_set", new HashSet<>(todoList))
                .apply();
    }

    private void loadTodoList() {
        Set<String> savedSet = getSharedPreferences("todo_data", MODE_PRIVATE)
                .getStringSet("todo_set", new HashSet<>());
        todoList.clear();
        todoList.addAll(savedSet);
        originalTodoList.clear();
        originalTodoList.addAll(todoList);
        todoAdapter.notifyDataSetChanged();
    }

    private void sortTodoList() {
        Collections.sort(todoList, (o1, o2) -> {
            // 1. 已完成状态优先（已完成后置）
            boolean isDone1 = o1.startsWith("[完成]");
            boolean isDone2 = o2.startsWith("[完成]");
            if (isDone1 != isDone2) {
                return isDone1 ? 1 : -1;
            }

            // 2. 提取两项的核心信息（去除[完成]前缀）
            String todo1 = isDone1 ? o1.substring(4) : o1;
            String todo2 = isDone2 ? o2.substring(4) : o2;

            // 3. 提取优先级（默认中优先级）
            int priority1 = getPriority(todo1);
            int priority2 = getPriority(todo2);
            int priorityResult = Integer.compare(priority2, priority1); // 优先级降序（高→低）
            if (priorityResult != 0) {
                return priorityResult;
            }

            // 4. 同优先级时按日期排序（无日期的默认排在后面）
            String date1 = getDateFromTodo(todo1);
            String date2 = getDateFromTodo(todo2);
            int dateResult = compareDates(date2, date1); // 日期近的在前（逆序比较）
            if (dateResult != 0) {
                return dateResult;
            }

            // 5. 无日期或日期相同时，按字符串逆序（新添加的在前）
            return todo2.compareTo(todo1);
        });

        todoAdapter.notifyDataSetChanged();
        saveTodoList(); // 保存排序结果
    }
    private int getPriority(String todo) {
        String strippedTodo = todo.startsWith("[完成]") ? todo.substring(4) : todo;
        if (strippedTodo.startsWith("[高]")) return 3;
        if (strippedTodo.startsWith("[中]")) return 2;
        if (strippedTodo.startsWith("[低]")) return 1;
        return 2; // 默认中优先级
    }
    // 从待办字符串中提取日期（格式：[YYYY-MM-DD]）
    private String getDateFromTodo(String todo) {
        // 匹配优先级后的日期标签，例如：[中][2025-06-05]内容 → 提取2025-06-05
        if (todo.startsWith("[低]") || todo.startsWith("[中]") || todo.startsWith("[高]")) {
            int startIndex = todo.indexOf('[', 1); // 第二个[的位置（优先级标签后）
            int endIndex = todo.indexOf(']', startIndex);
            if (startIndex != -1 && endIndex != -1) {
                return todo.substring(startIndex + 1, endIndex);
            }
        }
        return ""; // 无日期则返回空字符串
    }

    // 比较两个日期字符串（YYYY-MM-DD），返回正序比较结果（date1 > date2 → 1）
    private int compareDates(String date1, String date2) {
        if (date1.isEmpty() && date2.isEmpty()) {
            return 0; // 都无日期时视为相同
        } else if (date1.isEmpty()) {
            return 1; // 无日期的排在后面（date1空则视为更大）
        } else if (date2.isEmpty()) {
            return -1; // date2空则date1有日期，排在前面
        } else {
            // 按年-月-日拆分比较
            String[] parts1 = date1.split("-");
            String[] parts2 = date2.split("-");
            for (int i = 0; i < 3; i++) {
                int num1 = Integer.parseInt(parts1[i]);
                int num2 = Integer.parseInt(parts2[i]);
                if (num1 != num2) {
                    return num2 - num1;
                }
            }
            return 0; // 日期完全相同
        }
    }

    private void deleteAllCompleted() {
        new AlertDialog.Builder(this)
                .setTitle("批量删除")
                .setMessage("确定要删除所有已完成的待办事项吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    int size = todoList.size();
                    for (int i = size - 1; i >= 0; i--) {
                        if (todoList.get(i).startsWith("[完成]")) {
                            todoList.remove(i);
                        }
                    }

                    originalTodoList.clear();
                    originalTodoList.addAll(todoList);
                    todoAdapter.notifyDataSetChanged();
                    saveTodoList();
                    updateStats();
                    Toast.makeText(this, "已删除所有已完成事项", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void filterTodoList(String keyword) {
        todoList.clear();

        if (keyword.isEmpty()) {
            todoList.addAll(originalTodoList);
        } else {
            for (String item : originalTodoList) {
                if (item.contains(keyword)) {
                    todoList.add(item);
                }
            }
        }

        todoAdapter.notifyDataSetChanged();
    }

    private void updateStats() {
        int totalCount = todoList.size();
        int completedCount = 0;

        for (String item : todoList) {
            if (item.startsWith("[完成]")) {
                completedCount++;
            }
        }

        statsTextView.setText("总计: " + totalCount + " 项，已完成: " + completedCount);
    }
}